package com.dd.stack.redis.controller;

import com.dd.stack.redis.pojo.req.PublishMessageReq;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/1/30 17:08
 * @Description 发布订阅
 */
@Slf4j
@RestController
@Api(tags = "发布订阅")
@RequestMapping("/api/pubsub")
public class RedisPubSubController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发布消息到 Redis 频道
     * @param req 频道名称 + 消息内容
     * @return 返回发布结果
     */
    @PostMapping("/publish")
    public String publishMessage(@RequestBody PublishMessageReq req) {
        log.info("publishMessage req = {}", req);
        // 发布消息到指定频道
        stringRedisTemplate.convertAndSend(req.getChannel(), req.getMessage());
        return "Message published to channel " + req.getChannel() + ": " + req.getMessage();
    }
}